﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO.Ports;
using System.Windows.Forms;
using Infrastructure;
using Picking.Common;
using PickingBusiness;
using Picking_Winform.Util;
using LabelManager2;

namespace Picking_Winform
{
    public partial class DistributionOperationView : FormBase
    {
        private int currentWorkerCount = 0;
        private bool lightEnbale = true;
        private bool scannerEnbale = false;

        private string scannerPortWorker1 = string.Empty;
        private string scannerPortWorker2 = string.Empty;
        private string scannerPortWorker3 = string.Empty;

        private string printerNameWorker1 = string.Empty;
        private string printerNameWorker2 = string.Empty;
        private string printerNameWorker3 = string.Empty;

        private int printNum = 1;
        private List<Queue<string>> QueueList = new List<Queue<string>>();

        private WorkersAndLightsSetupModel modelWorkersAndLights = new WorkersAndLightsSetupModel();
        private SebangoAndDNoSetupModel modelSebangoDNo = new SebangoAndDNoSetupModel();
        private LightAndDNoSetupModel modelLightDNo = new LightAndDNoSetupModel();

        private InterfaceUpdateHandler InterfaceUpdateHandle;
        private InterfaceUpdateHandler LightTurnOffHandle;

        private List<string> lightNosWorker1 = new List<string>();
        private List<string> lightNosWorker2 = new List<string>();
        private List<string> lightNosWorker3 = new List<string>();

        private Dictionary<string, string> mapping = new Dictionary<string, string>
        {
            {"1","1"},{"2","2"},{"3","3"},{"4","4"},
            {"5","5"},{"6","6"},{"7","7"},{"8","8"},
            {"9","9"},{"A","10"},{"B","11"},{"C","12"},
            {"D","13"},{"E","14"},{"F","15"},{"G","16"},
            {"H","17"},{"I","18"},{"J","19"},{"K","20"},
            {"L","21"},{"M","22"},{"N","23"},{"O","24"},
            {"P","25"},{"Q","26"},{"R","27"},{"S","28"},
            {"T","29"},{"U","30"},{"V","31"},{"W","32"},
            {"X","33"},{"Y","34"},{"Z","35"},{"-","36"},
            {".","37"},{" ","38"},{"$","39"},{"/","40"},
            {"+","41"},{"%","42"},{"0","0"}
        };

        /// <summary>
        /// Constructor
        /// </summary>
        public DistributionOperationView()
        {
            InitializeComponent();
            string isEP = ConfigurationManager.AppSettings["IsElectricalParts"];
            if (isEP == null) isEP = "F";
            if (isEP == "F") this.btnLightEnbale.Visible = false;
            else this.btnLightEnbale.Visible = true;


            //Thread thread = new Thread(new ParameterizedThreadStart(TryToTurnOnLights));
            //thread.IsBackground = true;
            //thread.Start(SynchronizationContext.Current);
        }

        /// <summary>
        /// Get Form Width
        /// </summary>
        /// <returns></returns>
        protected override int GetFormWidth()
        {
            return 820;
        }

        /// <summary>
        /// Set Form Title
        /// </summary>
        private void SetFormTitle()
        {
            this.Text = "配送作业";
            this.lblLineName.Text = ConfigInfo.LineName;
            this.lblWorkerNumber.Text = "（" + this.currentWorkerCount.ToString() + "人）";
        }

        /// <summary>
        /// Form Shown
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DistributionOperationView_Shown(object sender, EventArgs e)
        {
            this.SetFormTitle();
            this.TurnOnLEDGreen();
        }

        /// <summary>
        /// Form Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DistributionOperationView_Load(object sender, EventArgs e)
        {
            this.GetWorkersAndLightsSetup();
            this.InitOperationArea();

            this.InitSebangoAndDNoSetup();
            this.InitLightAndDNoSetup();

            this.InitQueue();

            this.InterfaceUpdateHandle
                = new InterfaceUpdateHandler(UpdateTextBox);

            this.LightTurnOffHandle
                = new InterfaceUpdateHandler(HandleTurnedOffLightNo);

            this.InitAIPlug();

#if DEBUG
            this.lblSebangoTest.Visible = true;
            this.cmbSebangoTest.Visible = true;
            this.cmbSerialPortTest.Visible = true;
            this.btnTest.Visible = true;
            this.btnClearTest.Visible = true;

            this.cmbSebangoTest.Items.Add("t910111231012341001G");
            this.cmbSebangoTest.Items.Add("t910211232098762020$");
#endif
        }

        private void InitQueue()
        {
            for (int i = 0; i < this.currentWorkerCount; i++)
            {
                QueueList.Add(new Queue<string>());
            }
        }

        /// <summary>
        /// Get Current WorkersAndLightsSetup Data From Database
        /// </summary>
        private void GetWorkersAndLightsSetup()
        {
            this.modelWorkersAndLights = PickingBusiness.Configuration.GetWorkersAndLightsSetup();

            this.currentWorkerCount = modelWorkersAndLights.WorkersAndLightsSetupTable.Rows.Count;
        }

        /// <summary>
        /// Init Operation Area
        /// </summary>
        private void InitOperationArea()
        {
            if (this.currentWorkerCount <= 0)
            {
                this.tlpMain.Visible = false;
            }
            else if (this.currentWorkerCount <= 1)
            {
                this.tlpOperationArea2.Visible = false;
                this.tlpOperationArea3.Visible = false;

                this.tlpMain.ColumnStyles.Clear();
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 150F));
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 150F));

                float lblFontSize = 20F;
                float txtFontSize = 30F;
                // Set Font                
                this.lblProduct1.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.lblSebango1.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.lblRemainPiece1.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtProduct1.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtSebango1.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtRemainPiece1.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            }
            else if (this.currentWorkerCount <= 2)
            {
                this.tlpOperationArea3.Visible = false;

                this.tlpMain.ColumnStyles.Clear();
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 30F));
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 30F));
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
                this.tlpMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 30F));

                float lblFontSize = 20F;
                float txtFontSize = 30F;
                // Set Font
                this.lblProduct1.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.lblSebango1.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.lblRemainPiece1.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtProduct1.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtSebango1.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtRemainPiece1.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

                // Set Font
                this.lblProduct2.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.lblSebango2.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.lblRemainPiece2.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtProduct2.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtSebango2.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtRemainPiece2.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            }
            else if (this.currentWorkerCount <= 3)
            {
                float lblFontSize = 20F;
                float txtFontSize = 30F;
                // Set Font
                this.lblProduct1.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.lblSebango1.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.lblRemainPiece1.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtProduct1.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtSebango1.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtRemainPiece1.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

                // Set Font
                this.lblProduct2.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.lblSebango2.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.lblRemainPiece2.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtProduct2.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtSebango2.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtRemainPiece2.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

                // Set Font
                this.lblProduct3.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.lblSebango3.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.lblRemainPiece3.Font = new System.Drawing.Font("SimSun", lblFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtProduct3.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtSebango3.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                this.txtRemainPiece3.Font = new System.Drawing.Font("SimSun", txtFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            }
        }

        /// <summary>
        /// Init Sebango And DNo
        /// Get Sebango And DNo Setup From Database
        /// </summary>
        private void InitSebangoAndDNoSetup()
        {
            this.modelSebangoDNo = PickingBusiness.Configuration.GetSebangoAndDNoSetup();
        }

        /// <summary>
        /// Init DNo
        /// Get Light And DNo Setup From Database
        /// </summary>
        private void InitLightAndDNoSetup()
        {
            this.modelLightDNo = PickingBusiness.Configuration.GetLightAndDNoSetup();
        }

        /// <summary>
        /// Init AIPlug
        /// </summary>
        private void InitAIPlug()
        {
            if (!string.IsNullOrWhiteSpace(ConfigInfo.AxAiPlugIpAddress))
            {
                this.scannerPortWorker1 = ConfigurationManager.AppSettings["ScanGunPortWorker1"].ToString().Trim();
                this.scannerPortWorker2 = ConfigurationManager.AppSettings["ScanGunPortWorker2"].ToString().Trim();
                this.scannerPortWorker3 = ConfigurationManager.AppSettings["ScanGunPortWorker3"].ToString().Trim();

                this.printerNameWorker1 = ConfigurationManager.AppSettings["PrinterNameWorker1"].ToString().Trim();
                this.printerNameWorker2 = ConfigurationManager.AppSettings["PrinterNameWorker2"].ToString().Trim();
                this.printerNameWorker3 = ConfigurationManager.AppSettings["PrinterNameWorker3"].ToString().Trim();

                int printNumber = 1;

                if (int.TryParse(ConfigurationManager.AppSettings["PrintNum"].ToString().Trim(), out printNumber))
                {
                    if (printNumber > 0)
                    {
                        this.printNum = printNumber;
                    }
                }

                axAiPlug.ConnectSocket(ConfigInfo.AxAiPlugIpAddress, ConfigInfo.AxAiPlugPort);

                axAiPlug.StartPolling(); //watch the data arrival

                axAiPlug.BinaryMode = true; //set to true

                axAiPlug.CommandTimeout = 5000; //set to 5000

                this.axAiPlug.DataArrival
                    += new AxAiPlugControl.@__AiPlug_DataArrivalEventHandler(this.axAiPlug_DataArrival);

                this.OpenAllSanner();
            }
        }

        /// <summary>
        /// Open All Sanner
        /// </summary>
        private void OpenAllSanner()
        {
            if (!string.IsNullOrWhiteSpace(this.scannerPortWorker1))
            {
                axAiPlug.SendCommand("G" + this.scannerPortWorker1 + "o");
                this.scannerEnbale = true;
            }

            if (!string.IsNullOrWhiteSpace(this.scannerPortWorker2))
            {
                axAiPlug.SendCommand("G" + this.scannerPortWorker2 + "o");
                this.scannerEnbale = true;
            }

            if (!string.IsNullOrWhiteSpace(this.scannerPortWorker3))
            {
                axAiPlug.SendCommand("G" + this.scannerPortWorker3 + "o");
                this.scannerEnbale = true;
            }
        }

        /// <summary>
        /// Close All Sanner
        /// </summary>
        private void CloseAllSanner()
        {
            if (!string.IsNullOrWhiteSpace(this.scannerPortWorker1))
            {
                axAiPlug.SendCommand("G" + this.scannerPortWorker1 + "c");
            }

            if (!string.IsNullOrWhiteSpace(this.scannerPortWorker2))
            {
                axAiPlug.SendCommand("G" + this.scannerPortWorker2 + "c");
            }

            if (!string.IsNullOrWhiteSpace(this.scannerPortWorker3))
            {
                axAiPlug.SendCommand("G" + this.scannerPortWorker3 + "c");
            }

            this.scannerEnbale = false;
        }

        /// <summary>
        /// Is No Remain Piece
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        private bool IsAllNoRemainPiece()
        {
            if ((string.IsNullOrEmpty(this.txtRemainPiece1.Text.Trim())
                    || string.Equals(this.txtRemainPiece1.Text.Trim(), "0"))
                    && (string.IsNullOrEmpty(this.txtRemainPiece2.Text.Trim())
                    || string.Equals(this.txtRemainPiece2.Text.Trim(), "0"))
                    && (string.IsNullOrEmpty(this.txtRemainPiece3.Text.Trim())
                    || string.Equals(this.txtRemainPiece3.Text.Trim(), "0")))
            {
                return true;
            }

            return false;
        }

        //private void TryToTurnOnLights(object context)
        //{
        //    while (true)
        //    {
        //        if (mre.WaitOne())
        //        {
        //            if (this.currentWorkerCount == 2)
        //            {
        //                if (this.lightNosWorker2.Count == 0 && this.SebangoListB.Count > 0)
        //                {
        //                    string sebango = this.SebangoListB.Dequeue();
        //                    SynchronizationContext con = context as SynchronizationContext;
        //                    con.Send(p =>
        //                    {
        //                        this.txtSebango2.Text = sebango;
        //                        this.lightNosWorker2.Clear();
        //                        this.DisplayLightNo(this.ltvLight2, this.txtSebango2.Text.Trim(), 2);
        //                        if (this.ltvLight2.Items.Count > 0) this.TurnOnLight(this.lightNosWorker2);
        //                    }, null);
        //                    mre.Reset();
        //                }
        //            }
        //            else if (this.currentWorkerCount == 3)
        //            {
        //                SynchronizationContext con = context as SynchronizationContext;

        //                int currentRemainPiece1 = 0;
        //                string remainPiece1 = this.txtRemainPiece1.Text.Trim();
        //                int.TryParse(remainPiece1, out currentRemainPiece1);

        //                int currentRemainPiece2 = 0;
        //                string remainPiece2 = this.txtRemainPiece2.Text.Trim();
        //                int.TryParse(remainPiece2, out currentRemainPiece2);

        //                if ((currentRemainPiece1 == 0)
        //                    && (currentRemainPiece2 != 0))
        //                {
        //                    con.Send(p =>
        //                    {
        //                        this.lightNosWorker2.Clear();
        //                        this.DisplayLightNo(this.ltvLight2, this.txtSebango2.Text.Trim(), 2);
        //                        if (this.ltvLight2.Items.Count > 0) this.TurnOnLight(this.lightNosWorker2);
        //                    }, null);
        //                    mre.Reset();
        //                }
        //                else if (currentRemainPiece2 == 0)
        //                {
        //                    con.Send(p =>
        //                    {
        //                        this.lightNosWorker3.Clear();
        //                        this.DisplayLightNo(this.ltvLight3, this.txtSebango3.Text.Trim(), 3);
        //                        if (this.ltvLight3.Items.Count > 0) this.TurnOnLight(this.lightNosWorker3);
        //                    }, null);
        //                    break;
        //                }
        //            }
        //        }
        //        else
        //        {
        //            Thread.Sleep(1000);
        //        }
        //    }
        //}

        /// <summary>
        /// Update Text Box
        /// </summary>
        /// <param name="text"></param>
        /// <param name="portName"></param>
        private void UpdateTextBox(string text, string port)
        {
            if (this.currentWorkerCount <= 0)
            {
                return;
            }


            if (ConfigurationManager.AppSettings["IsElectricalParts"] != "T") text = text.Substring(1, text.Length - 1);
            string productName = this.GetProductName(text.Trim());
            string sebango = this.GetSebango(text.Trim());
            string remainPiece = this.GetRemainPiece(text.Trim());
            string sequence = this.GetSequence(text.Trim());

            int remainPieceNumber = 0;
            int.TryParse(remainPiece, out remainPieceNumber);

            //这个方法是在扫描枪扫描的时候执行的
            //当一个条码被扫描之后，将这个条码保存到所有打开的流水线的队列里面去
            for (int i = 0; i < this.currentWorkerCount; i++)
            {
                Queue<string> q = QueueList[i];
                q.Enqueue(text);
            }

            if (this.currentWorkerCount <= 1)
            {
                this.txtProduct1.Text = productName;
                this.txtSebango1.Text = sebango;
                this.txtRemainPiece1.Text = remainPiece;

                if (this.lightEnbale)
                {
                    if (remainPieceNumber > 0)
                    {
                        this.lightNosWorker1.Clear();
                        this.DisplayLightNo(this.ltvLight1, this.txtSebango1.Text.Trim(), 1);

                        if (this.ltvLight1.Items.Count > 0)
                        {
                            this.TurnOnLight(this.lightNosWorker1);
                        }
                        else
                        {
                            this.txtRemainPiece1.Text = "0";
                        }
                    }
                }

                if (string.Equals(ConfigInfo.IsPrint.ToUpper(), "T"))
                {
                    this.Print(this.printerNameWorker1, ConfigInfo.LineName, ConfigInfo.LineCode,
                               sebango, remainPiece, sequence, productName);
                }
            }
            else if (this.currentWorkerCount <= 2)
            {
                this.txtProduct1.Text = productName;
                this.txtSebango1.Text = sebango;
                this.txtRemainPiece1.Text = remainPiece;



                if (ConfigurationManager.AppSettings["IsElectricalParts"] == "T")
                {
                    this.txtProduct2.Text = productName;
                    this.txtSebango2.Text = sebango;
                    this.txtRemainPiece2.Text = remainPiece;
                    if (this.lightEnbale)
                    {
                        if (remainPieceNumber > 0)
                        {
                            this.lightNosWorker1.Clear();
                            this.DisplayLightNo(this.ltvLight1, this.txtSebango1.Text.Trim(), 1);

                            this.lightNosWorker2.Clear();
                            this.DisplayLightNo(this.ltvLight2, this.txtSebango2.Text.Trim(), 2);

                            if (this.ltvLight1.Items.Count > 0)
                            {
                                this.TurnOnLight(this.lightNosWorker1);
                            }
                            else
                            {
                                this.txtRemainPiece1.Text = "0";
                            }

                            if (this.ltvLight2.Items.Count > 0)
                            {
                                this.TurnOnLight(this.lightNosWorker2);
                            }
                            else
                            {
                                this.txtRemainPiece2.Text = "0";
                            }
                        }
                    }

                    if (string.Equals(ConfigInfo.IsPrint.ToUpper(), "T"))
                    {
                        this.Print(this.printerNameWorker1, ConfigInfo.LineName, ConfigInfo.LineCode,
                                   sebango, remainPiece, sequence, productName);

                        this.Print(this.printerNameWorker2, ConfigInfo.LineName, ConfigInfo.LineCode,
                                   sebango, remainPiece, sequence, productName);
                    }
                }
                else
                {
                    this.lightNosWorker1.Clear();
                    this.DisplayLightNo(this.ltvLight1, this.txtSebango1.Text.Trim(), 1);
                    if (this.ltvLight1.Items.Count > 0) this.TurnOnLight(this.lightNosWorker1);
                    if (string.Equals(ConfigInfo.IsPrint.ToUpper(), "T"))
                    {
                        this.Print(this.printerNameWorker1, ConfigInfo.LineName, ConfigInfo.LineCode,
                                   sebango, remainPiece, sequence, productName);

                        this.Print(this.printerNameWorker2, ConfigInfo.LineName, ConfigInfo.LineCode,
                                   sebango, remainPiece, sequence, productName);
                    }
                }
            }
            else
            {
                this.txtProduct1.Text = productName;
                this.txtSebango1.Text = sebango;
                this.txtRemainPiece1.Text = remainPiece;

                this.txtProduct2.Text = productName;
                this.txtSebango2.Text = sebango;
                this.txtRemainPiece2.Text = remainPiece;

                this.txtProduct3.Text = productName;
                this.txtSebango3.Text = sebango;
                this.txtRemainPiece3.Text = remainPiece;

                if (ConfigurationManager.AppSettings["IsElectricalParts"] == "T")
                {
                    if (this.lightEnbale)
                    {
                        if (remainPieceNumber > 0)
                        {
                            this.lightNosWorker1.Clear();
                            this.DisplayLightNo(this.ltvLight1, this.txtSebango1.Text.Trim(), 1);

                            this.lightNosWorker2.Clear();
                            this.DisplayLightNo(this.ltvLight2, this.txtSebango2.Text.Trim(), 2);

                            this.lightNosWorker3.Clear();
                            this.DisplayLightNo(this.ltvLight3, this.txtSebango3.Text.Trim(), 3);

                            if (this.ltvLight1.Items.Count > 0)
                            {
                                this.TurnOnLight(this.lightNosWorker1);
                            }
                            else
                            {
                                this.txtRemainPiece1.Text = "0";
                            }

                            if (this.ltvLight2.Items.Count > 0)
                            {
                                this.TurnOnLight(this.lightNosWorker2);
                            }
                            else
                            {
                                this.txtRemainPiece2.Text = "0";
                            }

                            if (this.ltvLight3.Items.Count > 0)
                            {
                                this.TurnOnLight(this.lightNosWorker3);
                            }
                            else
                            {
                                this.txtRemainPiece3.Text = "0";
                            }
                        }
                    }

                    if (string.Equals(ConfigInfo.IsPrint.ToUpper(), "T"))
                    {
                        this.Print(this.printerNameWorker1, ConfigInfo.LineName, ConfigInfo.LineCode,
                                   sebango, remainPiece, sequence, productName);

                        this.Print(this.printerNameWorker2, ConfigInfo.LineName, ConfigInfo.LineCode,
                                   sebango, remainPiece, sequence, productName);

                        this.Print(this.printerNameWorker3, ConfigInfo.LineName, ConfigInfo.LineCode,
                                   sebango, remainPiece, sequence, productName);
                    }
                }
                else
                {
                    this.lightNosWorker1.Clear();
                    this.DisplayLightNo(this.ltvLight1, this.txtSebango1.Text.Trim(), 1);
                    if (this.ltvLight1.Items.Count > 0) this.TurnOnLight(this.lightNosWorker1);
                    if (string.Equals(ConfigInfo.IsPrint.ToUpper(), "T"))
                    {
                        this.Print(this.printerNameWorker1, ConfigInfo.LineName, ConfigInfo.LineCode,
                                   sebango, remainPiece, sequence, productName);

                        this.Print(this.printerNameWorker2, ConfigInfo.LineName, ConfigInfo.LineCode,
                                   sebango, remainPiece, sequence, productName);

                        this.Print(this.printerNameWorker3, ConfigInfo.LineName, ConfigInfo.LineCode,
                                   sebango, remainPiece, sequence, productName);
                    }
                }
            }
        }

        /// <summary>
        /// Display Light No
        /// </summary>
        /// <param name="ltvLight"></param>
        /// <param name="inputSebangoNo"></param>
        /// <param name="workerNumber"></param>
        private void DisplayLightNo(ListView ltvLight, string inputSebangoNo, int workerNumber)
        {
            ltvLight.Items.Clear();

            string lightNoToTurnOn = string.Empty;
            int sebango = 0;

            if (int.TryParse(inputSebangoNo.Trim(), out sebango))
            {
                foreach (DataRow row in this.modelSebangoDNo.SebangoAndDNoSetupTable.Rows)
                {
                    int sebagoDNo = 0;

                    if (int.TryParse(row["Sebango_ID"].ToString().Trim(), out sebagoDNo))
                    {
                        if (sebango == sebagoDNo)
                        {
                            string currentDNo = row["Design_No"].ToString().Trim();
                            foreach (DataRow rowLight in this.modelLightDNo.LightAndDNoSetupTable.Rows)
                            {
                                if (string.Equals(currentDNo, rowLight["Design_No"].ToString().Trim()))
                                {
                                    string lightNo = rowLight["Light_No"].ToString().Trim();

                                    int lightNumber = -1;

                                    int.TryParse(lightNo, out lightNumber);

                                    int startLightNo = this.GetLightStartNo(workerNumber);
                                    int endLightNo = this.GetLightEndNo(workerNumber);

                                    if ((lightNumber >= startLightNo)
                                        && (lightNumber <= endLightNo))
                                    {
                                        ltvLight.Items.Add(lightNumber.ToString("0000"));

                                        if (workerNumber == 1)
                                        {
                                            this.lightNosWorker1.Add(lightNumber.ToString("0000"));
                                        }
                                        else if (workerNumber == 2)
                                        {
                                            this.lightNosWorker2.Add(lightNumber.ToString("0000"));
                                        }
                                        else if (workerNumber == 3)
                                        {
                                            this.lightNosWorker3.Add(lightNumber.ToString("0000"));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Print
        /// </summary>
        /// <param name="printerName"></param>
        /// <param name="lineName"></param>
        /// <param name="lineCode"></param>
        /// <param name="sebango"></param>
        /// <param name="remainPiece"></param>
        /// <param name="sequence"></param>
        /// <param name="productWC"></param>
        private void Print(string printerName, string lineName, string lineCode,
                           string sebango, string remainPiece,
                           string sequence, string productWC)
        {
            if (string.IsNullOrWhiteSpace(printerName))
            {
                return;
            }

            int remainPieceNumber = 0;
            int.TryParse(remainPiece, out remainPieceNumber);

            if (remainPieceNumber <= 0)
            {
                return;
            }

            Thread thread = new Thread(new ThreadStart(() =>
            {
                if (string.IsNullOrEmpty(printerName)) return;
                string filePath = AppDomain.CurrentDomain.BaseDirectory
                    + ConfigurationManager.AppSettings["TemplateFilePath"].ToString().Trim();

                ////string printerName = "";//set printer name
                LabelManager2.ApplicationClass application = new LabelManager2.ApplicationClass();
                LabelManager2.Document doc = application.Documents.Open(filePath, true);
                if (printerName != null)
                {
                    doc.Printer.SwitchTo(printerName);
                }
                FormVariables vars = doc.Variables.FormVariables;

                //barcode：01012341001D
                LabelManager2.Free free1 = doc.Variables.FormVariables.Item("B");
                free1.Value = lineName;    // "R1";//line name
                LabelManager2.Free free2 = doc.Variables.FormVariables.Item("WC");
                free2.Value = lineCode;    // "310";//line code
                LabelManager2.Free free3 = doc.Variables.FormVariables.Item("SEBANGO1");
                free3.Value = sebango;     // "1234";//背番号
                LabelManager2.Free free4 = doc.Variables.FormVariables.Item("ALL");
                free4.Value = remainPiece; // "10";//残留台数
                LabelManager2.Free free5 = doc.Variables.FormVariables.Item("JUNO");
                free5.Value = sequence;    // "01";//顺番
                LabelManager2.Free free6 = doc.Variables.FormVariables.Item("JIBU");
                free6.Value = productWC;   // "010";//电装品WC
                doc.PrintLabel(remainPieceNumber);
                doc.FormFeed();
                doc.Close(false);
                application.Quit();
            }));
            thread.IsBackground = true;
            thread.Start();
        }

        /// <summary>
        /// Turn On Light
        /// </summary>
        /// <param name="lightNos"></param>
        private void TurnOnLight(List<string> lightNos)
        {
            string lightNoToTurnOn = string.Empty;

            foreach (string item in lightNos)
            {
                lightNoToTurnOn += item + "88888";

                if (lightNoToTurnOn.Trim().Length >= (ConfigInfo.LightNumInOneCommand * 9))
                {
                    this.axAiPlug.SendCommand("P100" + lightNoToTurnOn.Trim());
                    lightNoToTurnOn = string.Empty;
                }
            }

            if (!string.IsNullOrEmpty(lightNoToTurnOn.Trim()))
            {
                this.axAiPlug.SendCommand("P100" + lightNoToTurnOn.Trim());
            }
        }

        /// <summary>
        /// Turn On LED Green
        /// </summary>
        private void TurnOnLEDGreen()
        {
            this.axAiPlug.SendCommand("T" + ConfigInfo.CmdLEDGreen.Trim());
        }

        /// <summary>
        /// Turn On LED Red
        /// </summary>
        private void TurnOnLEDRed()
        {
            this.axAiPlug.SendCommand("T" + ConfigInfo.CmdLEDRed.Trim());
        }

        /// <summary>
        /// Turn On LED Beep
        /// </summary>
        private void TurnOnLEDBeep()
        {
            this.axAiPlug.SendCommand("T" + ConfigInfo.CmdLEDBeep.Trim());
        }

        /// <summary>
        /// Turn On LED Red And Beep
        /// </summary>
        private void TurnOnLEDRedAndBeep()
        {
            this.TurnOnLEDRed();
            //this.TurnOnLEDBeep();
        }

        /// <summary>
        /// Do Validation
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private bool DoValidation(string data)
        {
            string errorMessage = "扫描的序列号不正确，请重新扫描。";

            try
            {
                if (!this.IsLineAAllLightsOff())
                {
                    return false;
                }

                if (data.Length < 20)
                {
                    throw new Exception(errorMessage);
                }

                string port = this.GetScannerPort(data);
                string dataStatus = this.GetDataStatus(data);
                int barcodeLength = this.GetBarcodeLength(data);
                string sn = this.GetBarcode(data, barcodeLength);

                if (!string.Equals(dataStatus, "1"))
                {
                    throw new Exception(errorMessage);
                }

                if (barcodeLength != sn.Length)
                {
                    throw new Exception(errorMessage);
                }

                if (!this.CheckSN(sn))
                {
                    throw new Exception(errorMessage);

#if DEBUG
                    throw new Exception(errorMessage + sn + port);
#endif
                }
            }
            catch (Exception ex)
            {
                this.txtStatus1.Text = ex.Message;
                this.txtStatus2.Text = ex.Message;
                this.txtStatus3.Text = ex.Message;

                return false;
            }

            string message = "条码读取正确";

            this.txtStatus1.Text = message;
            this.txtStatus2.Text = message;
            this.txtStatus3.Text = message;

            return true;
        }

        /// <summary>
        /// Check SN
        /// </summary>
        /// <param name="sn"></param>
        /// <returns></returns>
        private bool CheckSN(string sn)
        {
            bool isSNValid = false;
            string checkedStr = sn.Substring(0, sn.Length - 1);
            string finalStr = checkedStr;
            int bcc = 0;
            for (int i = 0; i < checkedStr.Length; i++)
            {
                int val = 0;
                string key = checkedStr[i].ToString();
                if (this.mapping.ContainsKey(key))
                {
                    val = int.Parse(this.mapping[key]);
                }

                bcc += val;
            }

            string value = (bcc % 43).ToString();
            string concatValue = string.Empty;
            if (this.mapping.ContainsValue(value))
            {
                concatValue = this.mapping.First(p => p.Value == value).Key;
            }

            finalStr = finalStr + concatValue;
            isSNValid = (sn == finalStr);
            return isSNValid;
        }

        /// <summary>
        /// Get Light Start No
        /// </summary>
        /// <param name="workerNumber"></param>
        /// <returns></returns>
        private int GetLightStartNo(int workerNumber)
        {
            int startLightNo = 0;

            foreach (DataRow row in this.modelWorkersAndLights.WorkersAndLightsSetupTable.Rows)
            {
                if (string.Equals(row["Picking_Worker_No"].ToString().Trim(), workerNumber.ToString()))
                {
                    int.TryParse(row["Light_Start_No"].ToString().Trim(), out startLightNo);
                }
            }

            return startLightNo;
        }

        /// <summary>
        /// Get Light End No
        /// </summary>
        /// <param name="workerNumber"></param>
        /// <returns></returns>
        private int GetLightEndNo(int workerNumber)
        {
            int endLightNo = 0;

            foreach (DataRow row in this.modelWorkersAndLights.WorkersAndLightsSetupTable.Rows)
            {
                if (string.Equals(row["Picking_Worker_No"].ToString().Trim(), workerNumber.ToString()))
                {
                    int.TryParse(row["Light_End_No"].ToString().Trim(), out endLightNo);
                }
            }

            return endLightNo;
        }

        /// <summary>
        /// Get Product Name
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string GetProductName(string text)
        {
            string productName = string.Empty;
            productName = text.Substring(0, 3);

            return productName;
        }

        /// <summary>
        /// Get Sebango
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string GetSebango(string text)
        {
            string sebango = string.Empty;
            sebango = text.Substring(3, 4);

            return sebango;
        }

        /// <summary>
        /// Get Remain Piece
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string GetRemainPiece(string text)
        {
            string remainPiece = string.Empty;
            remainPiece = text.Substring(7, 2);
            int intV;
            if (!int.TryParse(remainPiece, out intV)) remainPiece = "01";

            return remainPiece;
        }

        /// <summary>
        /// Get Sequence
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string GetSequence(string text)
        {
            string sequence = string.Empty;
            sequence = text.Substring(9, 2);

            return sequence;
        }

        /// <summary>
        /// Get Scanner Port
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private string GetScannerPort(string data)
        {
            string scannerPort = string.Empty;
            scannerPort = data.Substring(1, 4);

            return scannerPort;
        }

        /// <summary>
        /// Get Data Status
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private string GetDataStatus(string data)
        {
            string status = string.Empty;
            status = data.Substring(5, 1);

            return status;
        }

        /// <summary>
        /// Get Barcode Length
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private int GetBarcodeLength(string data)
        {
            string barcodeLength = string.Empty;
            barcodeLength = data.Substring(6, 2);

            return int.Parse(barcodeLength);
        }

        /// <summary>
        /// Get Barcode
        /// </summary>
        /// <param name="data"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        private string GetBarcode(string data, int length)
        {
            string barcode = string.Empty;
            barcode = data.Substring(8, length);

            return barcode;
        }

        /// <summary>
        /// Get Light No
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private string GetLightNo(string data)
        {
            string lightNo = string.Empty;
            lightNo = data.Substring(1, 4);

            return lightNo;
        }

        /// <summary>
        /// Get Light Status
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private string GetLightStatus(string data)
        {
            string status = string.Empty;
            if (data.Length >= 7)
            {
                status = data.Substring(5, 2);
            }
            else if (data.Length >= 6)
            {
                status = data.Substring(5, data.Length - 5);
            }

            return status;
        }

        /// <summary>
        /// Handle Turned Off Light No
        /// </summary>
        /// <param name="data"></param>
        /// <param name="port"></param>
        private void HandleTurnedOffLightNo(string data, string port)
        {
            if (this.currentWorkerCount <= 0)
            {
                return;
            }

            string lightNo = this.GetLightNo(data);
            string lightStatus = this.GetLightStatus(data);

            if (this.currentWorkerCount <= 1)
            {
                this.ClearLightNo(this.ltvLight1, lightNo, lightStatus, this.txtRemainPiece1, this.lightNosWorker1, 0);
            }
            else if (this.currentWorkerCount <= 2)
            {
                this.ClearLightNo(this.ltvLight1, lightNo, lightStatus, this.txtRemainPiece1, this.lightNosWorker1, 0);
                this.ClearLightNo(this.ltvLight2, lightNo, lightStatus, this.txtRemainPiece2, this.lightNosWorker2, 1);
            }
            else
            {
                this.ClearLightNo(this.ltvLight1, lightNo, lightStatus, this.txtRemainPiece1, this.lightNosWorker1, 0);
                this.ClearLightNo(this.ltvLight2, lightNo, lightStatus, this.txtRemainPiece2, this.lightNosWorker2, 1);
                this.ClearLightNo(this.ltvLight3, lightNo, lightStatus, this.txtRemainPiece3, this.lightNosWorker3, 2);
            }
        }

        /// <summary>
        /// Clear Light No
        /// </summary>
        /// <param name="ltvLight"></param>
        /// <param name="lightNo"></param>
        /// <param name="lightStatus"></param>
        private void ClearLightNo(ListView ltvLight, string lightNo, string lightStatus,
                                  TextBox txtRemainPiece, List<string> lightNos, int lineNum)
        {
            bool findLight = false;

            for (int i = ltvLight.Items.Count - 1; i >= 0; i--)
            {
                if (string.Equals(ltvLight.Items[i].Text.Substring(0, lightNo.Length), lightNo))
                {
                    findLight = true;

                    if (string.Equals(lightStatus, "00"))
                    {
                        ////ltvLight.Items[i].Remove();
                        ////ltvLight.Items[i].Text = lightNo;
                        ltvLight.Items[i].ForeColor = System.Drawing.Color.Gray;
                    }
                    else
                    {
                        ////ltvLight.Items[i].Text = lightNo;
                        ltvLight.Items[i].ForeColor = System.Drawing.Color.Red;
                        this.TurnOnLEDRedAndBeep();
                    }
                }
            }

            ////if (findLight && (ltvLight.Items.Count == 0))
            if (findLight && this.IsAllLightTurnedOff(ltvLight))
            {
                ltvLight.Items.Clear();

                int remainPiece = 0;

                int.TryParse(txtRemainPiece.Text.Trim(), out remainPiece);

                remainPiece--;
                if (lineNum == 0) TurnOnBeep0();
                if (lineNum == 1) TurnOnBeep1();
                if (lineNum == 2) TurnOnBeep2();

                if (remainPiece >= 0)
                {
                    txtRemainPiece.Text = remainPiece.ToString();

                    if (remainPiece > 0)
                    {
                        foreach (string item in lightNos)
                        {
                            ltvLight.Items.Add(item);
                        }

                        this.TurnOnLight(lightNos);
                    }
                    else
                    {
                        lightNos.Clear();
                        //如果当前流水线的棚灯已经全部熄灭，那么将该流水线对应的队列的序列号出列
                        QueueList[lineNum].Dequeue();
                        //如果当前流水线的棚灯已经全部熄灭，那么尝试将下一条流水线的棚灯打开
                        TurnOnLineLightsIfPossible();
                    }
                }
            }
        }

        private Thread thread = null;

        private void TurnOnBeep0()
        {
            axAiPlug.SendCommand("T80021");
            thread = new Thread(p =>
            {
                object[] obj = p as object[];
                Thread.Sleep(int.Parse(obj[2].ToString()));
                AxAiPlugControl.AxAiPlug plugin2 = obj[0] as AxAiPlugControl.AxAiPlug;
                string cmd = obj[1].ToString();
                plugin2.SendCommand(cmd);
            }, 0);
            thread.Start(new object[] { axAiPlug, "T80020", ConfigurationManager.AppSettings["BeepTime"] });
        }

        private void TurnOnBeep1()
        {
            axAiPlug.SendCommand("T80041");
            thread = new Thread(p =>
            {
                object[] obj = p as object[];
                Thread.Sleep(int.Parse(obj[2].ToString()));
                AxAiPlugControl.AxAiPlug plugin2 = obj[0] as AxAiPlugControl.AxAiPlug;
                string cmd = obj[1].ToString();
                plugin2.SendCommand(cmd);
            }, 0);
            thread.Start(new object[] { axAiPlug, "T80040", ConfigurationManager.AppSettings["BeepTime"] });
        }

        private void TurnOnBeep2()
        {
            axAiPlug.SendCommand("T80051");
            thread = new Thread(p =>
            {
                object[] obj = p as object[];
                Thread.Sleep(int.Parse(obj[2].ToString()));
                AxAiPlugControl.AxAiPlug plugin2 = obj[0] as AxAiPlugControl.AxAiPlug;
                string cmd = obj[1].ToString();
                plugin2.SendCommand(cmd);
            }, 0);
            thread.Start(new object[] { axAiPlug, "T80050", ConfigurationManager.AppSettings["BeepTime"] });
        }

        private void TurnOnLineLightsIfPossible()
        {
            for (int i = this.currentWorkerCount - 1; i >= 1; i--)
            {
                Queue<string> currentCheckQueue = QueueList[i];
                Queue<string> prevCheckQueue = QueueList[i - 1];

                //当前队列的序列号数目比前一个队列的序列号数目多并且当前队列对应的流水线没有灯在打开状态下那么获取当前队列的
                //最前面一个序列号，并将该序列号对应的棚灯打开并显示，否则返回
                if (currentCheckQueue.Count <= prevCheckQueue.Count || IsCheckedQueueAlreadyHasLighsOn(i + 1)) continue;
                string sn = currentCheckQueue.Peek();

                //if (ConfigurationManager.AppSettings["IsElectricalParts"] != "T") sn = sn.Substring(1, sn.Length - 1);
                string productName = this.GetProductName(sn.Trim());
                string sebango = this.GetSebango(sn.Trim());
                string remainPiece = this.GetRemainPiece(sn.Trim());
                string sequence = this.GetSequence(sn.Trim());

                if (i == 2)
                {
                    this.txtProduct3.Text = productName;
                    this.txtSebango3.Text = sebango;
                    this.txtRemainPiece3.Text = remainPiece;

                    this.lightNosWorker3.Clear();
                    this.DisplayLightNo(this.ltvLight3, this.txtSebango3.Text.Trim(), 3);
                    if (this.ltvLight3.Items.Count > 0) this.TurnOnLight(this.lightNosWorker3);
                }
                else if (i == 1)
                {
                    this.txtProduct2.Text = productName;
                    this.txtSebango2.Text = sebango;
                    this.txtRemainPiece2.Text = remainPiece;

                    this.lightNosWorker2.Clear();
                    this.DisplayLightNo(this.ltvLight2, this.txtSebango2.Text.Trim(), 2);
                    if (this.ltvLight2.Items.Count > 0) this.TurnOnLight(this.lightNosWorker2);
                }
            }
        }


        private bool IsCheckedQueueAlreadyHasLighsOn(int checkedLine)
        {
            if (checkedLine == 2)
            {
                if (this.lightNosWorker2.Count > 0) return true;
                else return false;
            }
            else if (checkedLine == 3)
            {
                if (this.lightNosWorker3.Count > 0) return true;
                else return false;
            }
            return true;
        }

        /// <summary>
        /// Is All Light Turned Off
        /// </summary>
        /// <param name="ltvLight"></param>
        /// <returns></returns>
        private bool IsAllLightTurnedOff(ListView ltvLight)
        {
            bool isAllLightTurnedOff = true;

            for (int i = ltvLight.Items.Count - 1; i >= 0; i--)
            {
                if (ltvLight.Items[i].ForeColor != System.Drawing.Color.Gray)
                {
                    isAllLightTurnedOff = false;
                    break;
                }
            }

            return isAllLightTurnedOff;
        }

        /// <summary>
        /// Light Enbale
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLightEnbale_Click(object sender, EventArgs e)
        {
            if (this.lightEnbale)
            {
                this.lightEnbale = false;
                this.btnLightEnbale.Text = "棚灯无效（F6）";
                this.btnLightEnbale.FlatStyle = FlatStyle.Popup;
            }
            else
            {
                this.lightEnbale = true;
                this.btnLightEnbale.Text = "棚灯有效（F6）";
                this.btnLightEnbale.FlatStyle = FlatStyle.Standard;

                if (this.ltvLight1.Items.Count == 0)
                {
                    if (!string.Equals("0", this.txtRemainPiece1.Text.Trim()))
                    {
                        this.txtRemainPiece1.Text = string.Empty;
                    }
                }

                if (this.ltvLight2.Items.Count == 0)
                {
                    if (!string.Equals("0", this.txtRemainPiece2.Text.Trim()))
                    {
                        this.txtRemainPiece2.Text = string.Empty;
                    }
                }

                if (this.ltvLight3.Items.Count == 0)
                {
                    if (!string.Equals("0", this.txtRemainPiece3.Text.Trim()))
                    {
                        this.txtRemainPiece3.Text = string.Empty;
                    }
                }

                this.OpenAllSanner();
            }
        }

        /// <summary>
        /// Return Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReturn_Click(object sender, EventArgs e)
        {
            this.CloseCurrentWindow();
        }

        /// <summary>
        /// Form Resize
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DistributionOperationView_SizeChanged(object sender, EventArgs e)
        {
            this.tlpMain.Height = this.Height - 140;
        }

        /// <summary>
        /// Form Closing
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DistributionOperationView_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.axAiPlug.SendCommand("T80010");
            this.axAiPlug.SendCommand("T80020");
            this.axAiPlug.SendCommand("T80030");
            this.axAiPlug.SendCommand("T80040");
            this.axAiPlug.SendCommand("T80050");
            this.axAiPlug.StopPolling();
            this.axAiPlug.Dispose();
        }

        /// <summary>
        /// Test
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTest_Click(object sender, EventArgs e)
        {
            if (this.scannerEnbale)
            {
                AxAiPlugControl.__AiPlug_DataArrivalEvent e1
                    = new AxAiPlugControl.__AiPlug_DataArrivalEvent(this.cmbSebangoTest.Text);

                this.axAiPlug_DataArrival(null, e1);

                this.cmbSerialPortTest.Items.Clear();
                foreach (string item in this.lightNosWorker1)
                {
                    this.cmbSerialPortTest.Items.Add("t" + item + "00");
                }

                foreach (string item in this.lightNosWorker2)
                {
                    this.cmbSerialPortTest.Items.Add("t" + item + "00");
                }

                foreach (string item in this.lightNosWorker3)
                {
                    this.cmbSerialPortTest.Items.Add("t" + item + "00");
                }
            }

            AxAiPlugControl.__AiPlug_DataArrivalEvent e2
                = new AxAiPlugControl.__AiPlug_DataArrivalEvent(this.cmbSerialPortTest.Text);

            this.axAiPlug_DataArrival(null, e2);
        }

        /// <summary>
        /// Clear
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClearTest_Click(object sender, EventArgs e)
        {
            this.txtRemainPiece1.Text = string.Empty;
            this.txtRemainPiece2.Text = string.Empty;
            this.txtRemainPiece3.Text = "0";

            this.ltvLight1.Items.Clear();
            this.ltvLight2.Items.Clear();
            this.ltvLight3.Items.Clear();

            string message = "";

            this.txtStatus1.Text = message;
            this.txtStatus2.Text = message;
            this.txtStatus3.Text = message;

            this.btnLightEnbale.Enabled = true;
            this.OpenAllSanner();
        }

        /// <summary>
        /// axAiPlug Data Arrival
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void axAiPlug_DataArrival(object sender, AxAiPlugControl.__AiPlug_DataArrivalEvent e)
        {
            string data = e.data;
            //Scanner:
            //data=t910111251012341001I
            //t:fixed, 9101:port no. of the scan gun, 
            //1:normal(0:exception), 12:the length of the barcode, 
            //51012341001I:barcode

            //LightTurnOff:
            //data=t000100xxxx
            //t:fixed, 0001:light no, 
            //00:normal(else:exception)

            data = data.Replace("\n", string.Empty);
            data = data.Replace("\r", string.Empty);

            if (data.Length < 5)
            {
                return;
            }

            string port = this.GetScannerPort(data);

            if (string.Equals(this.scannerPortWorker1, port)
                || string.Equals(this.scannerPortWorker2, port)
                || string.Equals(this.scannerPortWorker3, port))
            {
                if (!this.DoValidation(data))
                {
                    return;
                }

                this.CloseAllSanner();

                int barcodeLength = this.GetBarcodeLength(data);
                string sn = this.GetBarcode(data, barcodeLength);

                if (InterfaceUpdateHandle != null)
                {
                    this.Invoke(InterfaceUpdateHandle,
                                new string[] { sn, port });
                }

                if (this.lightEnbale)
                {
                    this.btnReturn.Enabled = false;
                    this.btnLightEnbale.Enabled = false;
                }
            }
            else
            {
                if (LightTurnOffHandle != null)
                {
                    this.Invoke(LightTurnOffHandle,
                                new string[] { data, string.Empty });
                }
            }

            //check the comment of the method IsLineAAllLightsOff
            if (this.IsLineAAllLightsOff()) this.OpenAllSanner();
            //所有流水线的残留台数是0并且流水线对应的队列里面没有序列号了才可以点返回按钮
            if (this.IsAllNoRemainPiece() && this.IsAllQueueEmpty())
            {
                this.btnReturn.Enabled = true;
                this.btnLightEnbale.Enabled = true;
            }
        }

        private bool IsAllQueueEmpty()
        {
            bool isAllQueueEmpty = true;
            for (int i = 0; i < this.currentWorkerCount; i++)
            {
                if (QueueList[i].Count > 0) isAllQueueEmpty = false;
            }
            return isAllQueueEmpty;
        }

        //如果流水线A的残留台数是0（只有当A的所有棚灯全部熄灭后A的残留台数才会是0）
        //并且打开的最后一条流水线的剩余条码数（保存在最后一条流水线对应的队列中）与流水线A的剩余条码数的差额小于配置文件中
        //GapToStopScan的值时，扫描枪才可以继续打开使用
        private bool IsLineAAllLightsOff()
        {
            bool isLineALightsClear = false;
            if (string.IsNullOrEmpty(this.txtRemainPiece1.Text.Trim()) || string.Equals(this.txtRemainPiece1.Text.Trim(), "0"))
            {
                isLineALightsClear = true;
            }

            string gapToStopScan = ConfigurationManager.AppSettings["GapToStopScan"];
            int gap;
            if (!int.TryParse(gapToStopScan, out gap)) gap = 10;

            Queue<string> lastQueue = QueueList[this.currentWorkerCount - 1];
            Queue<string> QueueA = QueueList[0];
            if (lastQueue.Count - QueueA.Count < gap) return (true & isLineALightsClear);
            else return false;
        }
    }
}
